<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /* 返回json提示 */
    /* 已被废除 */
    // public function alertJson($info, $code = 0, $url = null, $data=null){
    // 	$arr = ['code'=> $code , 'msg' => $info];
    // 	if($url){

    //         //地址后植入menu_id
    //         $menu_id = request()->input('menu_id');
    //         if(!strpos('menu_id', $url) === false){
    //             if(strpos('?', $url)){
    //                 $url .= '&menu_id='.$menu_id;
    //             }else{
    //                 $url .= '?menu_id='.$menu_id;
    //             }
    //         }
    // 		$arr['url'] = $url;
            
    // 	}
    // 	if($data){
    // 		$arr['data'] = $data;
    // 	}
    // 	return response()->json($arr);
    // }

    protected function jump($info,$code,$url=null,$data=null){
        $arr = ['code'=>$code,'msg' =>$info];

        $jump_key = $code == 1?'jump_success_message':'jump_error_message';

        if($url){
            //地址后植入menu_id
            $menu_id = request()->input('menu_id');
            if(!strpos('menu_id', $url) === false){
                if(strpos('?', $url)){
                    $url .= '&menu_id='.$menu_id;
                }else{
                    $url .= '?menu_id='.$menu_id;
                }
            }
            $arr['url'] = $url;
            
        }

        if($data){
            $arr['data'] = $data;
        }

        //判断是否ajax
        if(request()->ajax()){
            return response()->json($arr);
        }else{

            //闪存数据
            if($data){
                session()->flash('jump_data',$arr['data']);
            }

            if(!$url){
                //返回至前一页
                return back()->with($jump_key,$info)->withInput();
            }else{
                return redirect($arr['url'])->with($jump_key,$info)->withInput();
            }
            
        }
    }

    public function success($info,$url=null,$data=null){
        return $this->jump($info,1,$url,$data);
    }

    public function error($info,$url=null,$data=null){
        return $this->jump($info,0,$url,$data);
    }
}
